"use strict";

import Vue from 'vue';
import axios from "axios";
import store  from '../store'  //获取 Tolen
import basepath from './base'//配置 api 访问域名地址

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

//请求拦截器
_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    //1. api 头
    config.url = basepath.apiUrl + config.url;

    //2. auth JWT Token
    config.headers.Authorization =  store.state.user.Token;
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
//响应拦截器
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    //res.status axios 的请求状态  200 成功  404 401
    if (response.status == 404) {
      console.log('地址错误');
    }
    return response.data;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  //全局挂载 axios
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
